<template>
  <div>
    <el-button type="primary" @click="openAddDialog">新增农业知识</el-button>
    <el-table :data="list" style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="summary" label="摘要" />
      <el-table-column prop="imageUrl" label="主图">
        <template slot-scope="scope">
          <el-image v-if="scope.row.imageUrl" :src="`/api${scope.row.imageUrl}`" style="width: 60px; height: 60px" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="small" @click="editRow(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRow(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增：图片裁剪对话框 -->
    <el-dialog title="图片裁剪" :visible.sync="cropperVisible" width="900px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="cropper-content">
        <vue-cropper ref="cropper" :img="cropImage" :info="true" :autoCrop="true" :autoCropWidth="300" :autoCropHeight="300" :fixedBox="true" :fixed="true"
          :fixedNumber="[1, 1]" :centerBox="true" outputType="png" :full="true" :canMove="true" :canMoveBox="true" :original="false" :enlarge="1"></vue-cropper>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cropperVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCropUpload">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品表单对话框（修改部分） -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="product-form">
        <!-- 左侧基本信息 -->
        <div class="form-left">
          <el-form-item label="标题">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="摘要">
            <el-input v-model="form.summary" />
          </el-form-item>
          <el-form-item label="主图" prop="imageUrl">
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUpload">
              <img v-if="form.imageUrl" :src="`/api${form.imageUrl}`" class="avatar" style="width: 100px; height: 100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- 额外图片（修改部分） -->
          <el-form-item label="额外图片" prop="extraImages">
            <el-upload 
              class="avatar-uploader" 
              action="#" 
              :multiple="true" 
              :show-file-list="false" 
              :auto-upload="false" 
              :on-change="handleExtraUpload"
              :on-remove="handleRemoveExtra"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="upload-list">
              <el-image 
                v-for="(img, index) in extraImageList" 
                :key="index" 
                :src="`/api${img}`" 
                style="width: 60px; height: 60px; margin: 8px 8px 0 0" 
                fit="cover"
              >
                <div slot="error" class="image-error">加载失败</div>
                <div slot="placeholder" class="image-placeholder"></div>
              </el-image>
            </div>
          </el-form-item>
          <!-- 右侧富文本编辑器 -->
          <div class="form-right">
            <el-form-item label="内容" prop="content" class="description-item">
              <div class="editor-wrapper">
                <Toolbar class="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
                <Editor class="editor-content" v-model="form.content" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Request from '@/utils/request'
import { getKnowledgeList, addKnowledge, updateKnowledge, deleteKnowledge } from '@/api/AgricultureKnowledgeController'
import { VueCropper } from 'vue-cropper'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: {
    VueCropper,
    Editor,
    Toolbar
  },
  data() {
    return {
      list: [],
      dialogVisible: false,
      dialogTitle: '',
      form: { id: null, title: '', summary: '', content: '', imageUrl: '', extraImages: '' },
      // 新增：图片裁剪相关
      cropperVisible: false,
      cropImage: '',
      uploadFile: null,
      // 新增：区分主图/额外图片裁剪
      cropperType: 'main', // 'main' or 'extra'
      pendingExtraFile: null, // 临时存储待裁剪的额外图片
      // 新增：富文本编辑器相关
      editor: null,
      mode: 'default',
      toolbarConfig: {
        excludeKeys: ['group-video'] // 移除视频功能
      },
      editorConfig: {
        placeholder: '请输入知识内容...',
        MENU_CONF: {
          uploadImage: {
            base64LimitSize: 5 * 1024 * 1024, // 5MB以下转base64
            customUpload: async (file, insertFn) => {
              try {
                const isImage = file.type.startsWith('image/')
                if (!isImage) {
                  this.$message.error('上传文件只能是图片格式!')
                  return
                }
                const fileSize = file.size / 1024 / 1024
                if (fileSize > 10) {
                  this.$message.error('图片大小不能超过 10MB!')
                  return
                }
                const formData = new FormData()
                formData.append('file', file)
                const res = await Request.post('/file/upload/img', formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data',
                    'token': this.userInfo?.token
                  }
                })
                if (res.code === '0') {
                  insertFn(`/api${res.data}`)
                  this.$message.success('图片上传成功')
                } else {
                  this.$message.error(res.msg || '图片上传失败')
                }
              } catch (error) {
                console.error('上传图片失败:', error)
                this.$message.error('图片上传失败')
              }
            }
          }
        }
      },
      // 新增：表单验证规则（修复rules未定义）
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
        imageUrl: [{ required: true, message: '请上传主图', trigger: 'change' }]
      },
      // 新增：额外图片列表（修复extraImageList未定义）
      extraImageList: []
    }
  },
  methods: {
    // 主图上传处理（参考ProductManager.vue）
    handleUpload(file) {
      const isImage = file.raw.type.startsWith('image/')
      const isLt10M = file.raw.size / 1024 / 1024 < 10
      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      this.uploadFile = file.raw
      this.cropperType = 'main'
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        this.cropImage = reader.result
        this.cropperVisible = true
      }
      return false // 阻止自动上传
    },
    // 额外图片上传处理（和主图一样裁剪上传）
    handleExtraUpload(file, fileList) {
      const isImage = file.raw.type.startsWith('image/')
      const isLt10M = file.raw.size / 1024 / 1024 < 10
      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      this.pendingExtraFile = file.raw
      this.cropperType = 'extra'
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        this.cropImage = reader.result
        this.cropperVisible = true
      }
      return false // 阻止自动上传
    },
    // 主图/额外图片裁剪上传（根据cropperType区分）
    async handleCropUpload() {
      try {
        const blob = await new Promise((resolve) => {
          this.$refs.cropper.getCropBlob((data) => resolve(data))
        })
        const fileName = `cropped-${Date.now()}.png`
        const file = new File([blob], fileName, { type: 'image/png' })
        const formData = new FormData()
        formData.append('file', file)
        const res = await Request.post('/file/upload/img', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'token': this.userInfo?.token
          }
        })
        if (res.code === '0') {
          if (this.cropperType === 'main') {
            this.form.imageUrl = res.data
            this.$message.success('主图上传成功')
          } else if (this.cropperType === 'extra') {
            this.extraImageList.push(res.data)
            this.form.extraImages = this.extraImageList.join(',')
            this.$message.success('额外图片上传成功')
          }
          this.cropperVisible = false
          this.cropperType = 'main'
          this.pendingExtraFile = null
        } else {
          throw new Error(res.msg || '上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error(error.message || '图片上传失败')
      }
    },
    // 富文本编辑器控制
    handleCreated(editor) {
      this.editor = Object.seal(editor)
    },
    handleChange(editor) {
      this.form.content = editor.getHtml() // 同步编辑器内容到form
    },
    loadList() {
      getKnowledgeList().then(res => {
        this.list = res
      })
    },
    openAddDialog() {
      this.dialogTitle = '新增农业知识'
      this.form = { id: null, title: '', summary: '', content: '', imageUrl: '', extraImages: '' }
      this.dialogVisible = true
    },
    editRow(row) {
      this.dialogTitle = '编辑农业知识'
      this.form = { ...row }
      this.dialogVisible = true
    },
    submitForm() {
      if (this.form.id) {
        updateKnowledge(this.form).then(() => {
          this.dialogVisible = false
          this.loadList()
        })
      } else {
        addKnowledge(this.form).then(() => {
          this.dialogVisible = false
          this.loadList()
        })
      }
    },
    deleteRow(id) {
      deleteKnowledge(id).then(() => {
        this.loadList()
      })
    },
    // 新增：移动额外图片处理方法到methods内（修复方法未定义）
    /**
     * 处理额外图片删除
     * @param {File} file 被删除的文件对象
     * @param {FileList} fileList 剩余文件列表
     */
    handleRemoveExtra(file, fileList) {
      // 注意：这里需要根据实际上传后的URL匹配删除（示例使用文件名匹配，实际可根据业务调整）
      const fileName = file.raw.name
      const index = this.extraImageList.findIndex(img => img.includes(fileName))
      if (index !== -1) {
        this.extraImageList.splice(index, 1)
        this.form.extraImages = this.extraImageList.join(',')
      }
    }
  },
  mounted() {
    this.loadList()
  }
}
</script>

<style scoped>
/* 新增编辑器样式 */
.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.editor-toolbar {
  border-bottom: 1px solid #dcdfe6;
  padding: 8px;
}
.editor-content {
  height: 260px;
  padding: 16px;
}
/* 图片上传样式 */
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}
.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  color: #8c939d;
  font-size: 28px;
}
/* 额外图片上传样式 */
.extra-uploader {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.upload-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.cropper-content {
  height: 600px;
  width: 100%;
}
:deep(.vue-cropper) {
  width: 100% !important;
  height: 600px !important;
}
:deep(.cropper-container) {
  width: 100% !important;
  height: 600px !important;
}
</style>